package top.szhome.framework.starter.boot.configuration;

import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import top.szhome.framework.core.tools.util.DateUtil;
import top.szhome.framework.starter.boot.jackson.SzhomeJavaTimeModule;

import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Jackson配置
 *
 * @author 唐加利
 * @date 2023/7/24
 **/
@AutoConfiguration
@ComponentScan(basePackages = "top.szhome.framework.starter.boot.web")
public class JacksonAutoConfiguration {

    /**
     * 配置Jackson行为
     *
     * @return
     */
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer customizer() {
        return builder -> {
            builder.featuresToEnable(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(),
                    JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER.mappedFeature(),
                    JsonReadFeature.ALLOW_SINGLE_QUOTES.mappedFeature(),
                    DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

            builder.featuresToDisable(SerializationFeature.FAIL_ON_EMPTY_BEANS,
                    SerializationFeature.FAIL_ON_SELF_REFERENCES,
                    SerializationFeature.FAIL_ON_UNWRAPPED_TYPE_IDENTIFIERS,
                    DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
                    SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,
                    MapperFeature.IGNORE_DUPLICATE_MODULE_REGISTRATIONS);
            builder.locale(Locale.CHINA);
            builder.timeZone((TimeZone.getTimeZone(ZoneId.systemDefault())));
            builder.dateFormat(new SimpleDateFormat(DateUtil.FORMAT_LONG, Locale.CHINA));
            builder.modules(SzhomeJavaTimeModule.INSTANCE);
            builder.findModulesViaServiceLoader(true);
        };
    }

}
